import { _decorator, Collider2D, IPhysics2DContact, Node, Prefab, Vec2 } from 'cc';
import Biz from '../../biz';
import Utils from '../../utils';
import { BulletConfig, getBulletConfig } from '../config/bullet';
import { AbstractEntity } from './common';
import { EventName } from '../../consts/events';
const { ccclass } = _decorator;

@ccclass('Bullet')
export class Bullet extends AbstractEntity {
    private config: BulletConfig;
    public init(name: string) {
        if (this.isInit) return;
        this.isInit = true;
        this.config = getBulletConfig(name);
        Utils.events.on(EventName.EndGame, this.onEndGame, this);
    }
    protected destructor(): void {
        Utils.events.on(EventName.EndGame, this.onEndGame, this);
    }
    private onEndGame(): void {
        this.exitTheWorld();
    }
    public joinTheWorld(): void {
        if (this.isJoinTheWorld) return;
        this.isJoinTheWorld = true;
        this.colliderBody.enabled = true;
        this.node.active = true;
        this.enabled = true;
    }
    public exitTheWorld(): void {
        if (!this.isJoinTheWorld) return;
        this.isJoinTheWorld = false;
        this.colliderBody.enabled = false;
        this.node.active = false;
        Utils.pool.returnNode(this.node);
    }

    protected update(dt: number): void {
        if (!Biz.global.isStart || !this.isJoinTheWorld) return;
        this.node.setPosition(this.node.position.x, this.node.position.y + this.config.speed * dt);
        if (this.node.position.y > Utils.sys.getPlatform().windowSize.height) {
            this.exitTheWorld();
        }
    }

    // 碰撞检测
    protected onPhysicsCollision(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (!this.isJoinTheWorld) return;
        if (Biz.judge.isBulletHit(otherCollider.node.name, this.config)) {
            this.exitTheWorld();
        }
    }
}

export const createBullet = (root: Node, prefab: Prefab, pos: Vec2) => {
    const body = Utils.pool.createNode(prefab);
    body.setParent(root);
    let bullet = body.getComponent(Bullet);
    if (!bullet) {
        bullet = body.addComponent(Bullet);
        bullet.init(prefab.name);
    }

    bullet.node.setPosition(pos.x, pos.y);
    bullet.joinTheWorld();
};
